<?php

namespace App\Http\Servers\Admin;


use Intervention\Image\Facades\Image;

class ImageServer
{
    private $image;

    public function __construct(\App\Image $image)
    {
        $this->image = $image;
    }

    //生成保存路径
    private function makeSavePath($path)
    {
        return "/public/uploads/" . $path . "/" . date('Ymd') . "/";
    }

    //图片上传
    public function uploadImage($file, $tag, $path = '')
    {
        $path = $this->makeSavePath($path);
        if (!file_exists('.' . $path)) {
            mkdir('.' . $path, 0777, true);
        }
        if (extension_loaded('fileinfo')) {
            $filename = uniqid() . mt_rand(11111, 99999) . '.' . $file->guessExtension();
            $img = Image::make($file)->save('.' . $path . $filename);
        } else {
            $ext = pathinfo(array_values($_FILES)[0]['name'])['extension'];
            $filename = uniqid() . mt_rand(11111, 99999) . '.' . $ext;
            $img = move_uploaded_file(array_values($_FILES)[0]['tmp_name'], '.' . $path . $filename);
        }

        if ($img) {
            $result = $this->image->create(['tag' => $tag, 'path' => $path . $filename]);
            if ($result) {
                return $result->id;
            } else {
                unlink('.' . $path . $filename);
                return false;
            }
        } else {
            return false;
        }
    }

    //删除图片
    public function deleteImage($id, $force = true)
    {
        $image = \App\Image::find($id);
        if (!$image) return;

        if (file_exists('.' . $image->path)) {
            return unlink('.' . $image->path) && $image->delete();
        }
    }

}